import { Table, } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import React, { useState, useEffect } from 'react';
import { getUserList, getUserCount } from "../../api/request.js";

interface DataType {
    registe_time: string
    username: string
    city: string
    id: number
}
const App: React.FC = () => {

    // 用户数量
    const [userCount, setUserCount] = useState(0)
    // 用户列表
    const [userList, setUserList] = useState([])
    // 页码
    const [current, setCurrent] = useState<number>(1)
    // 每页显示个数
    const [pageSize, setPageSize] = useState<number>(100)
    // 表格高度
    const [height] = useState(document.body.offsetHeight - 300)

    useEffect(() => {
        // 请求用户数量
        getUserCount().then(res => setUserCount(res.data.count))
    }, [])

    useEffect(() => {
        // 请求用户列表
        getUserList({ offset: current, limit: pageSize }).then(res => {
            console.log(res)
            setUserList(res.data)
        })
    }, [current, pageSize])


    // 表格处理
    const columns: ColumnsType<DataType> = [
        {
            title: '#',
            dataIndex: 'index',
            render: (text, record, index) => index + 1,
        },
        {
            title: '注册日期',
            dataIndex: 'registe_time',
        },
        {
            title: '用户姓名',
            dataIndex: 'username',
        },
        {
            title: '注册地址',
            dataIndex: 'city',
        }
    ];

    return (
        <div>
                <Table
                    columns={columns}
                    dataSource={userList}
                    rowKey={record => record.id}
                    pagination={{
                        pageSize,
                        total: userCount,
                        onChange: (page, pageSize) => {
                            setCurrent(page)
                            setPageSize(pageSize)
                        },
                        showTotal: total => <span>共有{total}条数据</span>
                    }}
                    scroll={{ y: height }}
                    bordered={true}
                />
        </div>
    );
};

export default App;